package com.un.ebs.core.util;

import com.un.ebs.core.exception.BusinessException;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liubo
 * @email liubocs@163.com
 * @date 2020/8/3 21:48
 */
public class ReportUtils {

    public static <T> void print(Object data, List<? super T> list, String templatePath, @NotNull HttpServletResponse response) {
        if (StringUtils.isNullOrEmpty(templatePath)) {
            throw new BusinessException("打印模板不能为空。");
        }

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        response.setContentType("application/pdf");
        Map<String, Object> mapNote = null;
        if (data != null) {
            mapNote = BeanUtils.beanToMap(data);
        }

        Map<String, Object> parameters = new HashMap<>();
        ClassPathResource resource = new ClassPathResource(templatePath);

        try {
            if (!resource.exists()) {
                throw new BusinessException(String.format("打印模板文件【%s】没有找到。", templatePath));
            }

            JasperReport report = JasperCompileManager.compileReport(resource.getInputStream());
            if (mapNote != null) {
                for (JRParameter p : report.getParameters()) {
                    parameters.put(p.getName(), mapNote.get(p.getName()));
                }
            }

            JRDataSource ds = null;
            if (!StringUtils.isNullOrEmpty(list)) {
                ds = new JRBeanCollectionDataSource(list);
            }

            JasperPrint print = JasperFillManager.fillReport(report, parameters, ds);
            ServletOutputStream outputStream = null;
            try {
                outputStream = response.getOutputStream();
            } catch (IOException e) {
                throw new BusinessException(e.getMessage());
            }
            JasperExportManager.exportReportToPdfStream(print, outputStream);
            try {
                outputStream.flush();
            } catch (IOException e) {
                throw new BusinessException(e.getMessage());
            }
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (JRException | IOException e) {
            throw new BusinessException(e.getMessage());
        }
    }
}
